import dayjs from "dayjs";
import cloneDeep from "lodash";
function imgUpload({
  filename = "",
  filePath = "",
  isShowLoading = "1",
  type = "img",
  filesize = '',
  success,
  fail,
}) {
  console.log(filename)
  const user = uni.getStorageSync("Accountinfo");
  const cloudserv =  uni.getStorageSync("cloudserv");
  const bucket = cloudserv.storage;
  const timestamp = Date.now();
  const date = dayjs(timestamp).format("YYYYMMDD");
  console.log(filePath)
  // 文件名前三位/文件业务类型/年月日/租户code/文件名.扩展名
  const n_type = [
    "bmp",
    "jpg",
    "png",
    "jpeg",
    "tif",
    "gif",
    "pcx",
    "tga",
    "exif",
    "fpx",
    "svg",
    "psd",
    "cdr",
    "pcd",
    "dxf",
    "ufo",
    "eps",
    "ai",
    "raw",
    "wmf",
    "webp",
    "avif",
    "apng",
  ].includes(filePath.substring(filePath.lastIndexOf(".") + 1))
    ? "img"
    : "att";
  const objectkey = `${filename.slice(0, 3)}/${n_type}/${date}/${
    user.tenantcode
  }/${filename}`;
  let aliyunServerURL;
  aliyunServerURL = `https://${bucket.storageurl}`;
  function failFn(err) {
    console.error("上传失败", err);
    uni.hideLoading();
    let errTip = err.errMsg
      ? "上传失败，请重新上传。" + err.errMsg + err.data
      : "上传失败，请重新上传。";
    if (
      err.errMsg &&
      (err.errMsg.indexOf("timeout") !== -1 ||
        err.errMsg.indexOf("请求超时") !== -1)
    ) {
      errTip = "上传超时，请重新上传。";
    }
    uni.showModal({
      title: "提示",
      content: errTip,
      showCancel: false,
      success(e) {
        if (e.confirm) {
          fail && fail(err);
        }
      },
    });
  }
  if (isShowLoading) {
    uni.showLoading({
      title: "上传中...",
      mask: true,
    });
  }
  console.log(`${import.meta.env.VITE_APP_UPFILE_URL}/wx/util/upload`,'=当前文件上传地址')
  let uploadConfig = {
    //   url: aliyunServerURL,
    url: `${import.meta.env.VITE_APP_UPFILE_URL}/wx/util/upload`,
    filePath: filePath,
    name: "file",
    header:{
      token:user.token
    },
    timeout: 60000,
    success: function (res) {
      let data = JSON.parse(res.data);
      if (res.statusCode === 200 && data.code == "200") {
        const url = `${aliyunServerURL}/${objectkey}`;
        // todo
        uni.hideLoading();
        let obj = {
          url,
          filesize:filesize,
          source: filename,
          datetime: timestamp.toString(),
        };
        if (type == "att") {
          obj.date = obj.datetime;
          obj.filename = obj.source;
          obj.url = obj.source;
        }
        success && success(obj);
      } else {
        failFn(res);
      }
    },
    fail: function (err) {
      failFn(err);
    },
    complete(res) {
      console.log(res);
    },
  };
  if (bucket.provider === "aliyun") {
    // const policyText = {
    //   expiration: "2050-01-01T12:00:00.000Z",
    //   conditions: [
    //     ["content-length-range", 0, 100 * 1024 * 1024], // 设置上传文件的大小限制,1048576000=1000mb
    //   ],
    // };
    // const policyBase64 = getPolicyBase64(policyText);
    // const signature = getSignature(cloud.accesskeysecret, policyBase64);
    uploadConfig = {
      ...uploadConfig,
      formData: {
        file: filePath,
        // authorization: "OSS " + cloud.accesskeyid + ":" + signature,
        objectKey: objectkey,
        // OSSAccessKeyId: cloud.accesskeyid,
        // policy: policyBase64,
        // Signature: signature,
        // success_action_status: "200",
        // "x-oss-security-token": cloud.securitytoken,
      },
    };
  } else {
    throw new Error("暂不支持上传至该类型存储");
  }
  // debugger
  uni.uploadFile(uploadConfig);
}

const getUrl = ({
  type,
  file,
  // https://help.aliyun.com/knowledge_detail/39530.html?spm=5176.21213303.J_6028563670.106.56613eda6XizEq&scm=20140722.S_help%40%40%E7%9F%A5%E8%AF%86%E7%82%B9%40%4039530.S_0.ID_39530-RL_%E6%9C%89%E6%95%88%E6%9C%9F-OR_s%2Bhelpproduct-V_1-P0_19
  // https://help.aliyun.com/document_detail/39607.htm?spm=a2c4g.11186623.2.6.275f46d5KfvnXR
  isPublicReading = true, // 是否公共读 是的话直接生成连接 否的话需要进行签名操作
  width,
  height,
  success,
}) => {
  const dealFile = file
  if (type === "file") {
    dealFile.datetime = dealFile.datetime || dealFile.date;
    dealFile.source = dealFile.source || dealFile.url;
    delete dealFile.date;
    delete dealFile.url;
  } else if (type === "rtxe") {
  } else if (type === "img") {

  }
  const user = uni.getStorageSync("Accountinfo");
  const cloudserv =  uni.getStorageSync("cloudserv");
  const date = dayjs(Number(dealFile.datetime || dealFile.date)).format(
    "YYYYMMDD"
  );
  let objectkey;
  if (type === "file") {
    objectkey = `${dealFile.source.slice(0, 3)}/att/${date}/${
      user.tenantcode
    }/${dealFile.source}`;
  } else if (type === "rtxe") {
    objectkey = `${dealFile.source.slice(0, 3)}/att/${date}/${
      user.tenantcode
    }/${dealFile.source}`;
  } else if (type === "img") {
    objectkey = `${dealFile.source.slice(0, 3)}/img/${date}/${
      user.tenantcode
    }/${dealFile.source}`;
  }
  let process = "";
  // process = 'image/resize,m_fixed,h_100'
  if (type === "img") {
    if (width || height) {
      process = `image/resize,m_fixed`;
      if (width) {
        process += `,w_${width}`;
      }
      if (height) {
        process += `,h_${height}`;
      }
    }
  }

  if (isPublicReading) {
      let url;
      if (process) {
        url = `https://${
          cloudserv.storage.storageurl
        }/${objectkey}?x-oss-process=${encodeURIComponent(process)}`;
      } else {
        url = `https://${cloudserv.storage.storageurl}/${objectkey}`;
      }
    
    success && success(url,file);
  }
};

const imgGetUrl = ({ file, width, height, success }) => {
  return getUrl({
    type: "img",
    file,
    width,
    height,
    success,
  });
 
};

const fileGetUrl = ({ file, success }) => {
  return getUrl({
    type: "file",
    file,
    success,
  });
};

const rtxeGetUrl = ({ file, success }) => {
  return getUrl({
    type: "rtxe",
    file,
    success,
  });
};

export default {
  imgUpload,
  imgGetUrl,
  fileGetUrl,
  rtxeGetUrl,
};
